package com.example.demo.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        System.out.println("前置拦截器生效了·····");
        Map<String,Object> map = new HashMap<>();
//获取请求头中的令牌
        String token = request.getHeader("token");
        System.out.println("token为"+token);
        try {

            if (token==null) {
                throw new RuntimeException("无token，请重新登录");
            }
            DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);//验证令牌
            Integer userId = JwtUtil.getUserId(tokenInfo);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("message", "无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("message", "token过期！");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("message", "token算法不一致！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("message", "token无效！");
        }
        // 手动返回一个json 字符串
        map.put("code", 400);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;

    }
}
